package com.mjk.common.web.getway.utils;


import com.mjk.common.util.ObjectUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.util.HashMap;
import java.util.Map;
/**
 * web相关工具类
 * @author mjk
 *
 */
public final class WebUtil {

	private WebUtil(){}

	private static final String UNKNOWN = "unknown";
	/**
	 * 獲取IP地址
     */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ObjectUtils.isEmpty(ip)) || (UNKNOWN.equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ObjectUtils.isEmpty(ip)) || (UNKNOWN.equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ObjectUtils.isEmpty(ip)) || (UNKNOWN.equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if ((ObjectUtils.isEmpty(ip)) || (UNKNOWN.equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if ((ObjectUtils.isEmpty(ip)) || (UNKNOWN.equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}

		if ((!ObjectUtils.isEmpty(ip)) && (!UNKNOWN.equalsIgnoreCase(ip)) && (ip.contains(","))) {
			ip = ip.substring(0, ip.indexOf(","));
		}
		return ip;
	}
	
	/**
	 * 从request里面获取 key得session值
     */
	public static Object getSession(HttpServletRequest request, String sessionKey) {
		return request.getSession().getAttribute(sessionKey);
	}
	/**
	 * 设置session
     */
	public static void putSession(HttpServletRequest request, String sessionKey, Object sessionValue) {
		request.getSession().setAttribute(sessionKey, sessionValue);
	}
	/**
	 * 移除session
     */
	public static void removeSession(HttpServletRequest request, String sessionKey) {
		request.getSession().removeAttribute(sessionKey);
	}
	/**
	 * 添加cookie
     */
	public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
		if(value == null){
			return;
		}
		Cookie cookie = new Cookie(name, value);
		cookie.setSecure(true);
		cookie.setHttpOnly(true);
		cookie.setPath("/");
		if (maxAge > 0) {
			cookie.setMaxAge(maxAge);
		}
		response.addCookie(cookie);
	}
	/**
	 * 更具cookie名称获取值
     */
	public static String getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie>  cookieMap = readCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie =  cookieMap.get(name);
			return cookie.getValue();
		}
		return null;
	}
	/**
	 * 读取所有cookie
     */
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie>  cookieMap = new HashMap<> ();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
		}
		return cookieMap;
	}
}